package com.cgl.until;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailSender {
    private static  final Logger logger = LoggerFactory.getLogger(EmailSender.class);
    public static Boolean sendCode(String email,String code){
        String senderEmail = PropertiesRead.read("senderEmail");
        String senderPassword = PropertiesRead.read("senderEmailPassword");
        String subject = "落叶无痕的个人博客注册验证码"; // 邮件主题
        String body = "验证码:"+code+"，欢迎注册。[落叶无痕的个人博客]"; // 邮件正文
        //发送邮件
        return  sendEmail(senderEmail,senderPassword,email,subject,body);
    }

    private static boolean sendEmail(String senderEmail, String senderPassword, String receiverEmail, String subject, String body) {
        // 配置SMTP服务器属性
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            // 创建邮件对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail)); // 设置发件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiverEmail)); // 设置收件人
            message.setSubject(subject); // 设置邮件主题
            message.setText(body); // 设置邮件正文

            // 发送邮件
            Transport.send(message);
            logger.info("Email sent successfully!");
            return true;
        } catch (MessagingException e) {
            logger.info("Failed to send email: " + e.getMessage());
            return false;
        }
    }
}
